class Scene extends GuaScene {
    constructor(game) {
        super(game)
        var self = this

        this.score = 0

        // 注册按键控制
        self.game.registerAction("d", function() {
            self.paddle.moveRight()
        })
        self.game.registerAction("a", function() {
            self.paddle.moveLeft()
        })
        window.addEventListener('keydown', function(event) {
            if (event.key == "e") {
                self.game.replaceSceneByName("editor")
            }
        })

    }

    switchFromOtherScene() {
        this.loadLevelFromSelected()
    }

    loadLevelFromSelected() {
        var level = window.document.getElementById("id-levels").selectedIndex + 1
        var items = this.game.globalConfig["levels"][level - 1]
        this.blocks = []
        for (var i = 0; i < items.length; i++) {
            var item = items[i]
            if (item.name == "paddle"){
                this.paddle = item 
            } 
            if (item.name == "ball") {
                this.ball = item 
                this.ball.fire()
            }
            if (item.name == "block") {
                this.blocks.push(item)
            }
        }
        this.items = items
    }

    draw() {
        // draw
        for (let i = 0; i < this.items.length; i++) {
            const element = this.items[i];
            this.game.drawImage(element)
        }
            // draw blocks
        this.game.context.strokeText('分数: ' + this.score, 20, 250)
    }

    update() {
        if (this.ball.y > this.paddle.y) {
            var end = new SceneEnd(this.game)
            this.game.replaceSceneByName("end")
        }
        this.ball.move()
            // 判断相撞
        if (this.paddle.collide(this.ball)) {
            // 这里应该调用一个 ball.反弹() 来实现
            this.ball.bounce()
        }
        // 判断 ball 和 blocks 相撞
        for (var i = 0; i < this.blocks.length; i++) {
            var block = this.blocks[i]
            if (block.collide(this.ball)) {
                // log('block 相撞')
                block.kill()
                this.ball.bounce()
                this.score += 100
            }
        }
    }

}